<template>
    <div>
        <!-- 功能按钮 -->
        <div style="margin-bottom: 10px; margin-top: 5px">
            <el-input placeholder="搜索品牌" @input="updateData" @clear="updateData" v-model="search" clearable
                style="width:250px" prefix-icon="el-icon-search"></el-input>
            <el-button style="margin-left:10px" type="primary" size="small" @click="updateData()">搜索</el-button>

            <el-button size="small" type="success" @click="clickAdd()">添加汽车<i
                    class="el-icon-circle-plus-outline"></i>
            </el-button>
        </div>

        <!--添加编辑弹窗表单-->
        <el-dialog title="汽车信息表单" :visible.sync="dialogFormVisible" width="50%">
            <el-form label-width="80px" :model="ruleForm" status-icon :rules="rules" ref="ruleForm" class="demo-ruleForm">
                <el-form-item label="汽车名称" prop="carName">
                    <el-input v-model="ruleForm.carName" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="汽车价格" prop="carPriceL carPriceH">
                    <el-input style="width: 100px;" v-model="ruleForm.carPriceL" autocomplete="off"></el-input> 万 -
                    <el-input style="width: 100px;" v-model="ruleForm.carPriceH" autocomplete="off"></el-input> 万
                </el-form-item>

                <el-form-item label="封面图片" prop="carCover">
                    <el-upload class="avatar-uploader" action="http://101.43.12.19:8082/file/upload" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="ruleForm.carCover" :src="ruleForm.carCover" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>

                </el-form-item>
                <el-form-item label="汽车品牌" prop="brandId">
                    <el-select v-model="ruleForm.brandId" filterable placeholder="请选择">
                        <el-option v-for="item in carBrands" :key="item.brandId" :label="item.brandName"
                            :value="item.brandId">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="汽车级别" prop="carClass">
                    <template>
                        <el-radio-group v-model="ruleForm.carClass">
                            <el-radio :label="0">轿车</el-radio>
                            <el-radio :label="1">SUV</el-radio>
                            <el-radio :label="2">MPV</el-radio>
                            <el-radio :label="3">跑车</el-radio>
                            <el-radio :label="4">微卡</el-radio>
                            <el-radio :label="5">轻客</el-radio>
                            <el-radio :label="6">其他</el-radio>
                        </el-radio-group>
                    </template>
                </el-form-item>

                <el-form-item label="口碑" prop="carScore">
                    <el-rate v-model="ruleForm.carScore" :colors="colors" style="margin-top: 10px;">
                    </el-rate>
                </el-form-item>

                <el-form-item label="其他描述" prop="carIntro">
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入内容"
                        v-model="ruleForm.carIntro">
                    </el-input>

                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelEdit()">取 消</el-button>
                <el-button type="primary" @click="saveCar('ruleForm')">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 管理图片和车型 -->
        <el-dialog title="汽车管理" :visible.sync="manageDialogVisible" width="90%" style="margin-bottom: 0px;">
            <h2 style="margin-top:0px">{{ manageingCar.carName }}</h2>

            <h1>车型管理 <el-button icon="el-icon-plus" size="mini" style="margin-left: 89.5%;" circle
                    @click="modelDialogVisible = true"></el-button></h1>
            <el-table :data="manageingModelList" border stripe style="width: 1300px;">
                <el-table-column align="center" prop="modelName" label="车型名称" width="100">
                </el-table-column>
                <el-table-column align="center" prop="modelPrice" label="价格">
                </el-table-column>
                <el-table-column align="center" prop="marketTime" label="上市时间">
                </el-table-column>
                <el-table-column align="center" prop="maxTorque" label="最大扭矩">
                </el-table-column>
                <el-table-column align="center" prop="wheelBase" label="轴距">
                </el-table-column>
                <el-table-column align="center" prop="capacity" label="油箱/电池">
                </el-table-column>
                <el-table-column align="center" prop="engineModel" label="引擎型号">
                </el-table-column>
                <el-table-column align="center" prop="displacement" label="排量">
                </el-table-column>
                <el-table-column align="center" prop="maxHorsepower" label="最大马力">
                </el-table-column>
                <el-table-column align="center" prop="driveMode" label="驱动方式">
                </el-table-column>
                <el-table-column align="center" prop="maxSpeed" label="最高车速">
                </el-table-column>
                <el-table-column label="操作" align="center" width="300px">
                    <template slot-scope="scope">
                        <el-button type="success" @click="editModel(scope.row)">编辑<i class="el-icon-edit"></i></el-button>
                        <el-popconfirm confirm-button-text='确定' cancel-button-text='取消' icon="el-icon-info" icon-color="red"
                            title="您确定删除吗？" @confirm="deleteModel(scope.row.modelId)" style="margin-left:10px">
                            <el-button type="danger" slot="reference">删除<i class="el-icon-remove-outline"></i>
                            </el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>


            <h1>图片管理 <el-button icon="el-icon-plus" size="mini" style="margin-left: 89.5%;" circle
                    @click="picDialogVisible = true"></el-button></h1>
            <el-table :data="manageingPicList" border stripe style="width: 1300px;">
                <el-table-column align="center" prop="picUrl" label="图片">
                    <template v-slot:default="scope">
                        <el-image :src="scope.row.picUrl" />
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="picIntro" label="图片描述">
                </el-table-column>
                <el-table-column label="操作" align="center" width="300px">
                    <template slot-scope="scope">
                        <el-button type="success" @click="editPic(scope.row)">编辑<i class="el-icon-edit"></i></el-button>
                        <el-popconfirm confirm-button-text='确定' cancel-button-text='取消' icon="el-icon-info" icon-color="red"
                            title="您确定删除吗？" @confirm="deletePic(scope.row.picId)" style="margin-left:10px">
                            <el-button type="danger" slot="reference">删除<i class="el-icon-remove-outline"></i>
                            </el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>

            <el-button @click="manageDialogVisible = false" type="success" style="margin-left: 91%;margin-top: 20px;">完
                成</el-button>
        </el-dialog>


        <!-- 添加车型弹窗 -->
        <el-dialog title="车型" :visible.sync="modelDialogVisible" width="70%" style="margin-bottom: 0px;">
            <el-form label-width="80px" :model="modelForm" status-icon :rules="modelRules" ref="ruleForm"
                class="demo-ruleForm">
                <el-form-item label="车型名称" prop="modelName">
                    <el-input v-model="modelForm.modelName" autocomplete="off"></el-input>
                </el-form-item>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="价格" prop="modelPrice">
                            <el-input style="width: 90%;" placeholder="万元" v-model="modelForm.modelPrice"
                                autocomplete="off"></el-input>
                        </el-form-item>

                        <el-form-item label="上市时间" prop="marketTime">
                            <el-date-picker v-model="modelForm.marketTime" type="date" placeholder="选择日期"></el-date-picker>
                        </el-form-item>

                        <el-form-item label="最大扭矩" prop="maxTorque">
                            <el-input style="width: 90%;" v-model="modelForm.maxTorque" autocomplete="off"></el-input>
                        </el-form-item>

                        <el-form-item label="轴距" prop="wheelBase">
                            <el-input style="width: 90%;" v-model="modelForm.wheelBase" autocomplete="off"></el-input>
                        </el-form-item>

                        <el-form-item label="邮箱/电池" prop="capacity">
                            <el-input style="width: 90%;" v-model="modelForm.capacity" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="发动机" prop="engineModel">
                            <el-input style="width: 90%;" v-model="modelForm.engineModel" autocomplete="off"></el-input>
                        </el-form-item>

                        <el-form-item label="排量" prop="displacement">
                            <el-input style="width: 90%;" v-model="modelForm.displacement" autocomplete="off"></el-input>
                        </el-form-item>

                        <el-form-item label="最大马力" prop="maxHorsepower">
                            <el-input style="width: 90%;" v-model="modelForm.maxHorsepower" autocomplete="off"></el-input>
                        </el-form-item>

                        <el-form-item label="驱动方式" prop="driveMode">
                            <el-input style="width: 90%;" v-model="modelForm.driveMode" autocomplete="off"></el-input>
                        </el-form-item>

                        <el-form-item label="最高车速" prop="maxSpeed">
                            <el-input style="width: 90%;" v-model="modelForm.maxSpeed" autocomplete="off"></el-input>
                        </el-form-item>

                    </el-col>
                </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelModelEdit()">取 消</el-button>
                <el-button type="primary" @click="saveModel('modelForm')">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 添加图片弹窗 -->
        <el-dialog title="图片" :visible.sync="picDialogVisible" width="50%" style="margin-bottom: 0px;">
            <el-form label-width="80px" :model="picForm" status-icon :rules="picRules" ref="ruleForm" class="demo-ruleForm">
                <el-form-item label="上传图片" prop="picUrl">
                    <el-upload class="avatar-uploader" action="http://101.43.12.19:8082/file/upload" :show-file-list="false"
                        :on-success="handlePicSuccess" :before-upload="beforeAvatarUpload"
                        style="width:178px ;margin:auto;">
                        <img v-if="picForm.picUrl" :src="picForm.picUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="图片介绍" prop="picIntro">
                    <el-input :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入图片描述" v-model="picForm.picIntro">
                    </el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelEdit()">取 消</el-button>
                <el-button type="primary" @click="savePic('ruleForm')">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="删除模式选择" width="30%">
            <el-button @click="cancelEditModel()">取 消</el-button>
            <el-button type="primary" @click="saveCar('ruleForm')">确 定</el-button>
        </el-dialog>



        <!-- 表格渲染 -->
        <el-table :data="tableData" border stripe style="width: 1300px;" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55">
            </el-table-column>

            <el-table-column align="center" prop="carCover" label="汽车封面" width="100">
                <template v-slot:default="scope">
                    <el-image :src="scope.row.carCover" />
                </template>
            </el-table-column>

            <el-table-column align="center" prop="carName" label="汽车名">
            </el-table-column>

            <el-table-column align="center" prop="carPriceL" label="最低价">
            </el-table-column>

            <el-table-column align="center" prop="carPriceH" label="最高价">
            </el-table-column>
            <el-table-column align="center" prop="carClass" label="种类编号">
            </el-table-column>
            <el-table-column align="center" prop="carScore" label="评分">

            </el-table-column>
            <el-table-column align="center" prop="carIntro" label="介绍">
            </el-table-column>

            <el-table-column label="操作" align="center" width="300px">
                <template slot-scope="scope">
                    <el-button type="success" @click="editStore(scope.row)">编辑<i class="el-icon-edit"></i></el-button>
                    <el-button type="success" @click="editCar(scope.row)">管理<i class="el-icon-edit"></i></el-button>
                    <el-popconfirm confirm-button-text='确定' cancel-button-text='取消' icon="el-icon-info" icon-color="red"
                        title="您确定删除吗？" @confirm="deleteStore(scope.row.carId)" style="margin-left:10px">
                        <el-button type="danger" slot="reference">删除<i class="el-icon-remove-outline"></i>
                        </el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="padding:10px 0;">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
                :page-sizes="[5, 10, 15, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
    </div>
</template>

<script>
export default {
    name: "Manage",
    data() {
        return {
            //表单验证规则
            ruleForm: {
                carName: '',
                carPriceL: '',
                carPriceH: '',
                carCover: '',
                carClass: '',
                brandId: '',
                carScore: '',
                carIntro: ''
            },
            modelForm: {
            },
            picForm: {
                picUrl: ''
            },
            rules: {
                carName: [{ required: true, message: '请输入品牌名称', trigger: 'blur' },],
                carPriceL: [{ required: true, message: '请输入品牌简介', trigger: 'blur' },],
                carPriceH: [{ required: true, message: '请上传品牌标志', trigger: 'blur' },],
                carCover: [{ required: true, message: '请上传品牌标志', trigger: 'blur' }],
                carClass: [{ required: true, message: '请上传品牌标志', trigger: 'blur' },],
                brandId: [{ required: true, message: '请上传品牌标志', trigger: 'blur' },],
                carIntro: [{ required: true, message: '请上传品牌标志', trigger: 'blur' },],
                carScore: [{ required: true, message: '请上传品牌标志', trigger: 'blur' },]
            },
            modelRules: {
            },
            picRules: {
            },
            tableData: [],
            currentPage: 1,
            pageSize: 5,
            search: "",
            total: 0,
            dialogFormVisible: false,
            form: {}, //弹窗表单内容,
            imageUrl: '',
            //title: "添加品牌",
            carBrands: [],
            carClassDic: {
                0: '轿车',
                1: 'SUV',
                2: 'MPV',
                3: '跑车',
                4: '微卡',
                5: '轻客',
                6: '其他'
            },
            manageingCar: {},      //管理的汽车
            manageingModel: {},
            manageingPic: {},
            manageDialogVisible: false,
            modelDialogVisible: false,
            picDialogVisible: false,
            manageingModelList: {},
            manageingPicList: {}

        }
    },
    methods: {
        /* 图片上传相关 */
        handleAvatarSuccess(res, file) {
            this.ruleForm.carCover = res.data;
            this.$message.success('上传成功');
        },
        handlePicSuccess(res, file) {
            debugger;
            this.picForm.picUrl = res.data;
            debugger;
            this.$message.success('上传成功');
        },

        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG && !isPNG) {
                this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return (isJPG || isPNG) && isLt2M;
        },


        handleSizeChange(val) {
            this.pageSize = val;
            console.log(`每页 ${val} 条`);
            this.updateData();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            console.log(`当前页: ${val}`);
            this.updateData();
        },
        handleSelectionChange(val) {
            console.log(val);
            this.multipleSelection = val;
        },
        updateData() {
            //debugger;
            this.$axios.get("/car/page", {
                params: {
                    pageNum: this.currentPage,
                    pageSize: this.pageSize,
                    carName: this.search
                }
            }).then(res => {
                //debugger;
                //console.log(res.data.records);
                this.tableData = res.data.data.records;
                this.total = res.data.data.total;
            });
        },
        cancelEdit() {
            this.dialogFormVisible = false;
            this.ruleForm = {};
        },
        cancelModelEdit() {
            this.modelDialogVisible = false;
            this.modelForm = {};
        },
        saveCar(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.$axios.post("/car/save", this.ruleForm).then(res => {
                        if (res) {
                            this.$message.success("保存成功");
                            this.ruleForm = {};
                            this.dialogFormVisible = false;
                            this.updateData();
                        }
                        else {
                            this.$message.error("保存失败");
                        }
                    });
                } else {
                    console.log('error submit!!');
                    this.$message.error("表单填写有误，无法提交！");
                    return false;
                }
            });
        },
        saveModel(formName) {
            //this.$refs[formName].validate((valid) => {
            //if (valid) {
            this.modelForm['carId'] = this.manageingCar.carId;
            this.$axios.post("/model/save", this.modelForm).then(res => {
                if (res) {
                    this.$message.success("保存成功");
                    this.modelForm = {};
                    this.modelDialogVisible = false;
                    this.LodeModels();
                    //this.updateData();
                }
                else {
                    this.$message.error("保存失败");
                }
            });
            //} else {
            //  console.log('error submit!!');
            // this.$message.error("表单填写有误，无法提交！");
            // return false;
            // }
            // });
        },
        savePic(formName) {
            //this.$refs[formName].validate((valid) => {
            //if (valid) {
            this.picForm['carId'] = this.manageingCar.carId;
            this.$axios.post("/pic/save", this.picForm).then(res => {
                if (res) {
                    this.$message.success("保存成功");
                    this.picForm = {};
                    this.picDialogVisible = false;
                    this.LodePics();
                    //this.updateData();
                }
                else {
                    this.$message.error("保存失败");
                }
            });
        },

        LodePics() {
            this.$axios.get("/pic/get", {
                params: {
                    carId: this.manageingCar.carId,
                }
            }).then(res => {
                if (res) {
                    this.manageingPicList = res.data.data;
                    //this.modelDialogVisible = false;
                    //this.updateData();
                }
                else {
                    this.$message.error("保存失败");
                }
            });
        },
        LodeModels() {
            this.$axios.get("/model/get", {
                params: {
                    carId: this.manageingCar.carId,
                }
            }).then(res => {
                if (res) {
                    this.manageingModelList = res.data.data;
                    //this.modelDialogVisible = false;
                    //this.updateData();
                }
                else {
                    this.$message.error("保存失败");
                }
            });
        },
        LodeBrands() {

            this.$axios.get("/brand/all").then(res => {
                //console.log(res)
                if (res) {

                    this.carBrands = res.data.data;
                    console.log(res.data.data);
                    //debugger;

                }
                else {
                    this.$message.error("加载品牌失败");
                }
            });
        },
        deleteStore(id) {

            this.$axios.post("/car/del", id).then(res => {
                if (res) {
                    this.$message.success("删除成功");
                    if ((this.total - 1) % this.pageSize == 0) {
                        this.currentPage = this.currentPage > 1 ? this.currentPage - 1 : 1;
                    }
                    this.updateData();
                }
                else {
                    this.$message.error("删除失败，请联系系统管理员处理！");
                }
            });

        },
        deleteModel(modelId) {
            this.$axios.post("/model/del", modelId).then(res => {
                if (res) {
                    this.$message.success("删除成功");
                    this.LodeModels();
                }
                else {
                    this.$message.error("删除失败，请联系系统管理员处理！");
                }
            });

        },

        deletePic(picId) {
            this.$axios.post("/pic/del", picId).then(res => {
                if (res) {
                    this.$message.success("删除成功");
                    this.LodePics();
                }
                else {
                    this.$message.error("删除失败，请联系系统管理员处理！");
                }
            });
        },

        //编辑数据
        editStore(row) {
            //赋值
            debugger;
            this.ruleForm = row;
            //显示编辑框
            this.dialogFormVisible = true;
        },
        editCar(row) {
            this.manageingCar = row;
            this.manageDialogVisible = true;
            this.LodeModels();
            this.LodePics();
        },
        editModel(row) {
            this.modelForm = row;
            this.modelDialogVisible = true;
            //this.LodeModels();
        },
        editPic(row) {
            this.picForm = row;
            this.picDialogVisible = true;
        },
        clear() {
            this.search = "";
            this.updateData();
        },
        clickAdd() {
            this.ruleForm = {};
            this.dialogFormVisible = true;
        }

    },
    computed: {
        carclass() {
            return this.carClassDic[1];
        }
    },
    created() {
        this.updateData();
        this.LodeBrands();
    },
}
</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

